package com.jy.app.lib.update;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;

import com.alibaba.fastjson.TypeReference;
import com.jy.app.lib.net.JsonHttpHandler;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.jy.app.lib.net.HttpResponseHandler;
import com.jy.app.lib.net.HttpUtil;
import com.jy.app.lib.utils.ApkUtils;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class AppUpdateManager {
	private static Context context;
	private static DownloadAndInstaller dApp;
	private static String url="";
	private static IOSDialog msg;//对话框
	private static boolean isDis = true; //是否显示对话框
	private static Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if (AppUpdateManager.msg!=null) {
				AppUpdateManager.msg.setProgressBar(msg.what);
				if (msg.what==100) {
					postDelayed(new Runnable() {
						@Override
						public void run() {
							System.exit(0);
						}
					},1500);
				}
			}
		};
	};

	public static void checkUpdate(Context Context,String Url){
		init(Context);
		url = Url;
		start();
	}

	private static void init(Context Context){
		try{
			context = Context;
			dApp = new DownloadAndInstaller(Context);
			dApp.setHandler(handler);
		}catch (Exception e){}
	}

	private static void start(){
		checkUpdate();
	}

	private static void checkUpdate() {
		RequestParams params = new RequestParams();
		params.put("version", ApkUtils.getVersionName(context));
		params.put("versionCode", ApkUtils.getVersionCode(context));
		Map<String,String> map = new HashMap<>();
		map.put("appType",UpdateManager.appType);
		map.put("clientType",UpdateManager.clientType);
		HttpUtil.get(url,map,new JsonHttpHandler<HashMap<String,String>>(new TypeReference<HashMap<String,String>>(){}){
			@Override
			public void onSuccess(final HashMap<String,String> update, String ms) {
				final UpdateInfo updateInfo = new UpdateInfo();
				updateInfo.setApkUrl(TextUtils.isEmpty(update.get("url"))?"":update.get("url"));
				updateInfo.setVersionName(TextUtils.isEmpty(update.get("versions"))?"":update.get("versions"));
				updateInfo.setVersionCode(TextUtils.isEmpty(update.get("versions_code"))?0:Integer.parseInt(update.get("versions_code")));
				updateInfo.setIntervalTime(0);
				updateInfo.setNote(update.get("note"));
				Map<String, String> tis = new HashMap<>();
				tis .put("0","请更新到"+updateInfo.getVersionName()+"体验最新版本");
				updateInfo.setUpdateTips(tis);
				int state = Integer.parseInt(update.get("state"));
				if (state == 0){
					if (UpdateManager.mHander!=null)UpdateManager.mHander.sendEmptyMessage(UpdateManager.CHECK_UPDARE_NEWEST);
					if (dApp!=null) dApp.stopService();
					return;
				}else if(state == 1){
					updateInfo.setForceUpdate("1");
				}else{
					updateInfo.setForceUpdate("0");
				}
				if (updateInfo.getVersionName().equals("v"+ApkUtils.getVersionName(context))||ApkUtils.getVersionCode(context)>updateInfo.getVersionCode()) {
					if (UpdateManager.mHander!=null)
						UpdateManager.mHander.sendEmptyMessage(UpdateManager.CHECK_UPDARE_NEWEST);
					if (dApp!=null) dApp.stopService();
					return;
				}
				if (context!=null && (new Date().getTime() >= new DownloadAppConfig(context).getNetUpDateTime()||updateInfo.isForceUpdate())) {
					isDis = isUpDate();
					new DownloadAppConfig(context).setNetUpDateTime(new Date().getTime() + updateInfo.getIntervalTime());
						msg = new IOSDialog(context).builder()
								.setTitle("更新到" + updateInfo.getVersionName()).setDisP(Gravity.LEFT)
								.setMsg(getUpdateContent(updateInfo.getUpdateTips(),updateInfo.getNote()))
								.setPositiveButton("确定", new OnClickListener() {
									@Override
									public void onClick(View v) {
										File file = checkApkVersionName(updateInfo.getVersionName());
										if (file != null) {
											UpDateAppService.installApk(file,context);
											if (dApp!=null) dApp.stopService();
										}else{
										if (updateInfo.getApkSize() < ApkUtils.getSDFreeSize()) {
											dApp.setUrl(updateInfo.getApkUrl());
											dApp.startDownLoad();
											setUpDateProgress(updateInfo.isForceUpdate());
										} else {
											msg = new IOSDialog(context).builder().setTitle("提示").setDisP(Gravity.LEFT)
													.setMsg("内存空间不足").setPositiveButton("确定", new OnClickListener() {
														@Override
														public void onClick(View v) {
															if (updateInfo.isForceUpdate()) {
																System.exit(0);
															} else {
																msg.dismiss();
																if (dApp!=null) dApp.stopService();
															}
														}
													});
											if (updateInfo.isForceUpdate()) {
												msg.setCanceledOnTouchOutside(false);
												msg.setCancelable(false);
											}
											msg.show();
										}
									}
									}

								});
						if (!updateInfo.isForceUpdate()) {
							msg.setNegativeButton("取消", new OnClickListener() {
								@Override
								public void onClick(View v) {
									if (dApp!=null) dApp.stopService();
									if (UpdateManager.mHander!=null)
										UpdateManager.mHander.sendEmptyMessage(UpdateManager.CHECK_UPDATE_IS_CLICK);
								}
							});

						}
							msg.setCanceledOnTouchOutside(false);
							msg.setCancelable(false);
						if (isDis || updateInfo.isForceUpdate()) {
							msg.show();
						} else {
							if (dApp!=null) dApp.stopService();
						}

				}else{
					UpdateManager.context  = null;
					if (dApp!=null) dApp.stopService();
				}
			}
			@Override
			public void onFailure(int failCode, String failSource) {
				if (dApp!=null) dApp.stopService();
			}
		});
	}

	private static void setUpDateProgress(boolean forceUpdate){
		msg = new IOSDialog(context).builder().setTitle("进度").setProgressBar(0).setDisP(Gravity.LEFT)
				;
		if (!forceUpdate) {
			msg.setPositiveButton("后台下载", new OnClickListener() {
				@Override
				public void onClick(View v) {}});
			msg.setNegativeButton("取消",new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (UpdateManager.mHander!=null)
						UpdateManager.mHander.sendEmptyMessage(UpdateManager.CHECK_UPDATE_IS_CLICK);
					dApp.setStopDown();
				}});
		}else {
			msg.setPositiveButton("  ",false, new OnClickListener() {
				@Override
				public void onClick(View v) { }});
		}
		msg.setCanceledOnTouchOutside(false);
		msg.setCancelable(false);
		msg.show();
	}

	private static String getUpdateContent(Map<String, String> data,String note){
		if (!TextUtils.isEmpty(note)){
			return note;
		}
		if (data == null) {
			return "发现新版本，确认立即更新 ？";
		}
		String content = "";
		for (int i = 0; i < data.size(); i++) {
			if (i!=data.size()-1) {
				content +=i+1+"."+data.get(i+"")+"\n";
			}else{
				content +=i+1+"."+data.get(i+"");
			}
		}
		if (content.equals("")) {
			content = "发现新版本，确认立即更新 ？" ;
		}
		return content;
	}

	private static Boolean isUpDate(){
		DownloadAppConfig config = new DownloadAppConfig(context);
		long upDateTime = config.getNetUpDateTime();
		Long nowTime = new Date().getTime();
		if (nowTime - upDateTime >0) {
			return true;
		}
		return false;
	}

	public static File checkApkVersionName(String name){
		File is = null;
		String pathName = new DownloadAppConfig(context).getDownLoadPathName();
		if (!TextUtils.isEmpty(pathName)){
			File file = new File(pathName);
			if (file.exists()){
				String apkVersionName = getApkVersionName(pathName);
				if (!TextUtils.isEmpty(apkVersionName)&&!TextUtils.isEmpty(name)&&name.equals(apkVersionName))
				    is = new File(pathName);
			}
		}
		return is;
	}

	@Nullable
	public static String getApkVersionName(String pathName){
		PackageManager pm = context.getPackageManager();
		PackageInfo info = pm.getPackageArchiveInfo(pathName, PackageManager.GET_ACTIVITIES);
		if(info != null){
			ApplicationInfo appInfo = info.applicationInfo;
			String appName = pm.getApplicationLabel(appInfo).toString();
			String packageName = appInfo.packageName;  //得到安装包名称
			String version=info.versionName;       //得到版本信息
			//显示图标
		return  version;
		}
		return null;
	}
}
